package com.user.query.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.user.query.dao.MenuMapper;
import com.user.query.dao.RoleMenuMapper;
import com.user.query.model.Menu;
import com.user.query.model.RoleMenu;
import com.user.query.model.User;
import com.user.query.service.MenuService;
import com.user.query.utils.ConstantUtils;
import com.user.query.utils.IDGenerator;
import com.user.query.utils.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;
	
	@Resource
	private RoleMenuMapper roleMenuMapper;
	
	@Override
	public Page<Menu> queryPage(Page<Menu> page) {
		page.setTotalRecord(menuMapper.countByPage(page));
		page.setResults(menuMapper.selectByPage(page));
		return page;
	}

	@Override
	public List<Menu> grep(Menu menu) {
		return menuMapper.selectModel(menu);
	}

	@Override
	public Menu get(String id) {
		return (Menu) menuMapper.selectByPrimaryKey(id);
	}

	@Override
	public void modifyOrAdd(Menu menu) {
		if(StringUtils.isEmpty(menu.getMenuId())) {
			menu.setMenuId(IDGenerator.getUUID());
			menu.setStatus(ConstantUtils.Status.OK);
			menuMapper.insert(menu);
		}else {
			menuMapper.updateByPrimaryKeySelective(menu);
		}
	}

	@Override
	public List<Menu> queryAllEffective() {
		Menu menu = new Menu();
		menu.setStatus(ConstantUtils.Status.OK);
		menu.setOrderByClause("sort");
		
		return this.grep(menu);
	}

	@Override
	public List<Menu> queryByLoginUser(User loginUser) {
		RoleMenu roleMenu = new RoleMenu();
		roleMenu.setRole(loginUser.getRoleId());
		List<RoleMenu> roleMenus = roleMenuMapper.selectModel(roleMenu);
		if(roleMenus != null && roleMenus.size() > 0) {
			String[] ids = new String[roleMenus.size()];
			for(int roleMenusIndex = 0; roleMenusIndex < roleMenus.size(); roleMenusIndex++) {
				ids[roleMenusIndex] = roleMenus.get(roleMenusIndex).getMenu();
			}
			Menu menu = new Menu();
			if(!"admin".equals(loginUser.getAccountNo())) {
				menu.setIds(ids);
			}
			menu.setStatus(ConstantUtils.Status.OK);
			menu.setOrderByClause("sort");
			
			return menuMapper.selectModel(menu);
		}
		return null;
	}

	@Override
	public List<Menu> queryAllByParentId(String parentId) {
		
		return menuMapper.queryAllByParentId(parentId);
	}
}
